package designpatterns.singleton;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;

/**
 * @author 李栋
 * @version 1.0.0
 * @className SinglePartternTest.java
 * @createTime 2021年06月11日 21:22:00
 */
public class SinglePartternTest {

    private static final Logger logger = LoggerFactory.getLogger(SinglePartternTest.class);


    @Test
    public void testOne() {
        LazySingleton instance = LazySingleton.getInstance();
        logger.info(String.valueOf(instance));

        HungrySingleton instanceOne = HungrySingleton.getInstance();
        logger.info(String.valueOf(instanceOne));

    }

    /**
     * 使用 class.newInstance new 出对象
     */
    @Test
    public void testTwo() {
        try {
            LazySingleton instance = LazySingleton.class.newInstance();
            logger.info(String.valueOf(instance));
        } catch (InstantiationException | IllegalAccessException e) {
            logger.error("Error Occur:{}", e.getMessage());
        }

    }

    /**
     * 使用getConstructor()
     */
    @Test
    public void testThree() {
        try {
            Constructor<LazySingleton> lazySingleton = LazySingleton.class.getDeclaredConstructor();
        } catch (NoSuchMethodException e) {
            logger.error("Error Occur:{}", e.getMessage());
        }
    }

    /**
     * 反射修改访问权限
     */
    @Test
    public void testFour() {
        Class<LazySingleton> lazySingletonClass = LazySingleton.class;
        try {
            Constructor<LazySingleton> declaredConstructor = lazySingletonClass.getDeclaredConstructor();
            // 设置私有方法可见
            declaredConstructor.setAccessible(true);
            LazySingleton lazySingleton = declaredConstructor.newInstance();
            logger.info(String.valueOf(lazySingleton));
        } catch (Exception e) {
            logger.error("Error Occur:{}", e.getMessage());
        }
    }


}
